<template>
  <div>
    <!-- 柱状图 -->
    <div :id="id" style="width: 100%; height: 300px;"></div>
  </div>
</template>

<script>
import echarts from 'echarts';
export default {
  props: {
    id: {
      type: String,
      default: () => {
        var d = new Date().getTime();
        if (
          window.performance &&
          typeof window.performance.now === "function"
        ) {
          d += performance.now(); //use high-precision timer if available
        }
        var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
          /[xy]/g,
          function(c) {
            var r = (d + Math.random() * 16) % 16 | 0; // d是随机种子
            d = Math.floor(d / 16);
            return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
          }
        );
        return uuid;
      },
    },
    data: {
      type: Object || Array,
      default: () => {
        return {
          A1: -0.299,
          B1: -0.3,
          C1: 0.199,
          D1: 0,
          E1: -0.5,
          F1: -0.299,
        }
      }
    }
  },
  data() {
    return {
      myChart: null,
    }
  },
  watch: {
    data: {
      handler(value) {
        this.init(value)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    init(data) {
      this.$nextTick(() => {
        // 柱状图
        const histogram = document.getElementById(this.id);
        this.myChart = echarts.init(histogram);
        const { valeuDate, keys } = this.setData(data)

        const option = {
          color: '#3398DB',
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          animation: false,
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: [
            {
              type: "category",
              data: keys,
              axisTick: {
                alignWithLabel: true,
              },
              axisLabel: {
              fontSize: 16
            },
            },
          ],
          yAxis: [
            {
              type: "value",
              splitNumber: 4,
              axisLabel: {
                fontSize: 16
              },
            },
          ],
          series: {
            type: "bar",
            barWidth: "60%",
            data: valeuDate,
          }
        };

        this.myChart.setOption(option);
      })
    },
    resizeMyChart() {
      this.myChart.resize()
    },
    setData(data) {
      let keys = Object.keys(data)
      let valeuDate = []
      keys.forEach(item => {
        for (const k in data) {
          if(k === item) {
            valeuDate.push(data[k])
          }
        }
      })
      return {
        valeuDate,
        keys
      }
    }
  },

  beforeDestroy () {
    this.myChart.clear()
    window.removeEventListener('resize', this.resizeMyChart)
  },
}
</script>

<style>

</style>